import io from 'socket.io-client'
var CHAT = {
  msgObj: document.getElementsByClassName('chat-body')[0],
  UserName: null,
  WeChat: null,
  Uid: null,
  msgArr: [],
  aiMsgArr: [],
  onlineCount: 0,
  onlineUsers: null,
  // 初始化
  init: function () {
    // 获取登录信息
    this.UserName = localStorage.getItem('name')
    this.WeChat = localStorage.getItem('wechat')
    this.Uid = localStorage.getItem('uid')
    // 连接服务器
    this.socket = io('http://192.168.2.227:3000', {
      transports: ['websocket', 'polling']
    })
    // 将登录的用户信息发送给服务器
    this.socket.emit('login', {
      UserName: this.UserName,
      WeChat: this.WeChat,
      Uid: this.Uid
    })
    // 心跳包，30s左右无数据，浏览器会断开连接
    // setInterval(() => {
    //   this.socket.emit('heartbeat', 1)
    // }, 10000)
    // 监听新用户登陆
    this.socket.on('login', function (obj) {
      CHAT.updateSysMsg(obj, 'logout')
      CHAT.msgArr.push(obj)
    })
    // 修改用户信息
    this.socket.on('changeInfo', function (o) {
      CHAT.onlineUsers[o.userid] = o
    })
    // 监听用户退出
    this.socket.on('logout', function (o) {
      CHAT.updateSysMsg(o, 'logout')
    })
    // 监听消息发送
    this.socket.on('message', function (obj) {
      CHAT.msgArr.push(obj)
    })
    // 监听对机器人的消息发送
    this.socket.on('aimessage', function (obj) {
      CHAT.aiMsgArr.push(obj)
    })
  },
  updateSysMsg: function (o, action) {
    this.onlineUsers = o.onlineUsers
    this.onlineCount = o.onlineCount
    var user = o.user
    // 更新在线总人数
    var userhtml = ''
    var separator = ''
    console.log('这行没用---' + user + '' + userhtml + '' + separator + '---这行没用')
  },
  logout: function () {
    this.socket.disconnect()
  },
  submit: function (msg) {
    if (msg !== '') {
      let obj = {
        userid: this.Uid,
        username: this.UserName,
        msg: msg
      }
      console.log(obj)
      this.socket.emit('message', obj)
    } else {
      console.log('msg is null')
    }
    return false
  },
  // 监听对机器人的消息发送
  aiSubmit: function (aimsg) {
    if (aimsg !== '') {
      let obj = {
        userid: this.Uid,
        username: this.UserName,
        msg: aimsg,
        aimsg: aimsg
      }
      console.log(obj)
      this.socket.emit('aimessage', obj)
    } else {
      console.log('msg is null')
    }
    return false
  },
  changeInfo: function () {
    this.Uid = localStorage.getItem('userid')
    this.UserName = localStorage.getItem('name')
    this.WeChat = localStorage.getItem('weichat')
    // this.socket.emit('changeInfo', {Uid: this.uid, UserName: this.UserName, WeChat: this.WeChat})
  }
}

export default CHAT
